package org.zoomdev.zoom.lock.modules;

import org.zoomdev.zoom.lock.Executor;
import org.zoomdev.zoom.lock.LockExecutor;
import org.zoomdev.zoom.lock.LockFactory;

/**
 *
 */
class ObjectLockExecutor implements LockExecutor {

    private final ObjectLockFactory factory;

    public ObjectLockExecutor(LockFactory<Object> lockFactory) {
        factory = (ObjectLockFactory) lockFactory;
    }


    public Object execute(String key, Executor executor) throws Throwable {
        Object lock = factory.fetch(key);
        try {
            synchronized (lock) {
                return executor.execute();
            }
        } finally {
            factory.release(key, lock);
        }


    }
}
